﻿using System;
using System.Collections.Generic;

namespace Murry.DataStore.MemoryDB
{
    /// <summary>
    /// MemoryDB implementation of a DataStore.
    /// </summary>
    //public class MemoryDataStore : DataStore<Dictionary<Type, Dictionary<string, IPersist>>>, IDataStore
   public class MemoryDataStore : DataStore<MemoryDatabase>
   {
        /// <summary>
        /// Standard constructor.
        /// </summary>
        public MemoryDataStore()
        {
            Database = new MemoryDatabase();
        }

        /// <summary>
        /// Find all objects of a given type.
        /// </summary>
        /// <typeparam name="TInterface">Interface type</typeparam>
        /// <returns>Objects</returns>
        public override IEnumerable<TInterface> FindAll<TInterface>() 
        {
            var implementedType = Entities.GetImplementedEntityType(GetType(), typeof(TInterface));

            lock (Database)
            {
                return Database.GetQueryable<TInterface>(implementedType);
            }
        }

        /// <summary>
        /// Find object by ID.
        /// </summary>
        /// <typeparam name="TInterface">Interface type</typeparam>
        /// <param name="id">Object ID</param>
        /// <returns>Object</returns>
        public override TInterface FindById<TInterface>(string id) 
        {
            var implementedType = Entities.GetImplementedEntityType(GetType(), typeof(TInterface));

            lock (Database)
            {
                return Database.FindById<TInterface>(implementedType, id);
            }
        }

        /// <summary>
        /// Helper method to register entities.
        /// </summary>
        /// <param name="interfaceType">Interface type.</param>
        /// <param name="implementationType">Implemented type.</param>
        public static void RegisterEntity(Type interfaceType, Type implementationType)
        {
            Entities.AddEntity(typeof(MemoryDataStore), interfaceType, implementationType);
        }
    }
}
